﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ReportBusiness
{
    public class TreeObject
    {
        //全局变量用于保存数据
        private List<TreeObject> treeNode = new List<TreeObject>();

        public string label { get; set; }
        public string value { get; set; }

        public IList<TreeObject> children = new List<TreeObject>();

        /// <summary>
        /// 递归生产树
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="parentNode">父节点</param>
        /// <param name="parentID">节点的归属id</param>
        public List<TreeObject> BindTree(DataTable dtSource, TreeObject parentNode, string parentID)
        {
            DataRow[] rows = dtSource.Select(string.Format("parentid = '{0}'", parentID));
            foreach (DataRow row in rows)
            {
                TreeObject tree = new TreeObject();
                tree.label = row["label"].ToString();
                tree.value = row["id"].ToString();

                //递归
                BindTree(dtSource, tree, row["id"].ToString());

                // 如果没有子节点，将children设为null
                if (tree.children.Count == 0)
                {
                    tree.children = null;
                }

                if (parentNode == null)
                {
                    treeNode.Add(tree);
                }
                else
                {
                    parentNode.children.Add(tree);
                }
            }
            return treeNode;
        }

    }
}
